package com.sevntu.apvs.lab3;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class SourceData {

	private int[][] netMatrix = null;
	private int netMatrixLine = -1;
	private int netMatrixColumn = -1;
	private int elemMatrixLine = -1;
	private int elemMatrixColumn = -1;

	public SourceData(final String sourceFile) {
		readSourceData(sourceFile);
	}

	public int getNetMatrixLine() {
		return netMatrixLine;
	}

	public int getNetMatrixColumn() {
		return netMatrixColumn;
	}

	public int getElemMatrixLine() {
		return elemMatrixLine;
	}

	public int getElemMatrixColumn() {
		return elemMatrixColumn;
	}

	public int[][] getNetElemMatrix() {
		return netMatrix;
	}

	private void readSourceData(final String sourceFile) {
		BufferedReader inputFile = null;

		try {
			inputFile = new BufferedReader(new FileReader(sourceFile));
			String readLine;
			String fileData[];
			int countLine = 0;

			while ((readLine = inputFile.readLine()) != null) {
				readLine = readLine.trim();
				fileData = readLine.split("\\s+");

				switch (countLine) {
				case 0: {
					netMatrixLine = Integer.decode(fileData[0]);
					netMatrixColumn = Integer.decode(fileData[1]);
					if (netMatrixLine > 17 || netMatrixColumn > 17) {
						System.err.println("Wrong net matrix size!!");
						System.exit(0);
					}
					netMatrix = new int[netMatrixLine][netMatrixColumn];
				}
					break;
				case 1: {
					elemMatrixLine = Integer.decode(fileData[0]);
					elemMatrixColumn = Integer.decode(fileData[1]);
					if (elemMatrixLine > 17 || elemMatrixColumn > 17) {
						System.err.println("Wrong element matrix size!!");
						System.exit(0);
					}
				}
					break;
				default: {
					if (fileData.length > netMatrixColumn || (countLine - 1) > netMatrixLine || fileData.length < 2) {
						System.err.println("Wrong net matrix!!");
						System.exit(0);
					}
					for (int i = 0; i < fileData.length; i++) {
						netMatrix[countLine - 2][i] = Integer.decode(fileData[i]);
						if (netMatrix[countLine - 2][i] > 1 || netMatrix[countLine - 2][i] < 0) {
							System.err.println("Wrong data in net matrix!!");
							System.exit(0);
						}
					}
				}
				}
				countLine++;
			}
			if ((countLine - 2) != netMatrixLine) {
				System.err.println("Wrong net matrix!!");
				System.exit(0);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputFile != null) {
					inputFile.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
